<?php
$db = Db::getInstance();
$db->autocommit(false);
try {
	if($_SERVER['REQUEST_METHOD'] == 'POST'){
		if($_POST['operation'] == 'changePassword'){
			$query = sprintf("SELECT * FROM Account WHERE id='%s'", $db->real_escape_string(Authenticate::getId()));
			$result = $db->query($query);
			if(!$result){
				throw new Exception($db->error);
			}
			$account = $result->fetch_assoc();
			if(md5($_POST['oldPassword'])!=$account['password']){
				throw new Exception('password เก่าไม่ถูกต้อง', 300);
			}
			Account::instance()->changePassword(Authenticate::getId(), $_POST['newPassword']);
			$db->commit();
			echo json_encode(array('success'=> true));
		}
		else if($_POST['operation']=='uploadCard'){
			if(!file_exists($_FILES['card']['tmp_name'])){
				throw new Exception('File upload not exits');
			}
			$extension = strtolower(pathinfo($_FILES['card']['name'], PATHINFO_EXTENSION));
			$allowed =  array('gif', 'png', 'jpg');
			if(!in_array($extension, $allowed)){
				throw new Exception('อนุญาติให้ upload ได้แค่ (gif, png, jpg)', 300);
			}
			list($width, $height) = getimagesize($_FILES['card']['tmp_name']);
			if($width > 800 || $height > 800){
				throw new Exception('อนุญาติให้รูปกว้างไม่เกิน 800px สูงไม่เกิน 600px', 300);
			}
			$fileName = Authenticate::getId().'.'.$extension;
			$query = sprintf("UPDATE Account SET cardPath='%s' WHERE id='%s'", $db->real_escape_string($fileName), Authenticate::getId());
			if(!$db->query($query)){
				throw new Exception($db->error);
			}
			if(!move_uploaded_file($_FILES['card']['tmp_name'], 'img/card/'.$fileName)){
				throw new Exception('move_uploaded_file failed');
			}
			$db->commit();
			echo json_encode(array('success'=> true, 'cardPath'=> 'img/card/'.$fileName));
		}
	}
} catch (Exception $ex) {
	$db->rollback();
	Log::error($ex);
	if($ex->getCode() == 300) {
		echo json_encode(array('success'=> false, 'message'=> $ex->getMessage()));
	}
	else {
		echo json_encode(array('success'=> false));
	}
}